package com.yupi.usercenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yupi.usercenter.common.ApiRestResponse;
import com.yupi.usercenter.contant.UserContant;
import com.yupi.usercenter.exception.UserCenterException;
import com.yupi.usercenter.exception.UserCenterExceptionEnum;
import com.yupi.usercenter.mapper.UserMapper;
import com.yupi.usercenter.model.domain.User;
import com.yupi.usercenter.model.request.UserLoginRequest;
import com.yupi.usercenter.model.request.UserRegisterRequest;
import com.yupi.usercenter.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户接口
 *
 * @author Administrator
 */

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private UserMapper userMapper;

    /**
     * 用户接口测试
     *
     * @return
     */
    @GetMapping("usertest")
    public ApiRestResponse userTest() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        List<User> users = userMapper.selectList(queryWrapper);
        return ApiRestResponse.success(users);

    }

    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    public ApiRestResponse userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {

        if (userRegisterRequest == null) {
            throw new UserCenterException(UserCenterExceptionEnum.PARAMS_ERROR);
        }

        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new UserCenterException(UserCenterExceptionEnum.PARAMS_ERROR);
        }

        long userId = userService.userRegister(userAccount, userPassword, checkPassword);
        return ApiRestResponse.success(userId);

    }

    /**
     * 用户登录
     *
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public ApiRestResponse userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {

        if (userLoginRequest == null) {
            throw new UserCenterException(UserCenterExceptionEnum.PARAMS_ERROR);
        }

        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new UserCenterException(UserCenterExceptionEnum.PARAMS_ERROR);
        }

        User safetyUser = userService.userLogin(userAccount, userPassword, request);
        return ApiRestResponse.success(safetyUser);

    }

    @GetMapping("/current")
    public ApiRestResponse getCurrentUser(HttpServletRequest request){
        User currentUser = (User) request.getSession().getAttribute(UserContant.USER_LOGIN_STATE);
        if (currentUser == null) {
            return ApiRestResponse.error(UserCenterExceptionEnum.PARAMS_ERROR);
        }

        // todo 查询用户是否合法，并返回脱敏的用户信息
        Long userId = currentUser.getId();
        User user = userService.getById(userId);
        User safetyUser = userService.getSafetyUser(user);
        return ApiRestResponse.success(safetyUser);
    }

    /**
     * 根据用户名模糊查询接口
     *
     * @param username
     * @return
     */
    @GetMapping("/search")
    public ApiRestResponse searchUsers(String username, HttpServletRequest request) {

        // 管理员鉴权
        if (!isAdmin(request)) {
            // 非管理员返回空数据
            return ApiRestResponse.error(UserCenterExceptionEnum.DEFAULT_ERROR_CODE, "用户不是管理员，返回空");
        }

        return ApiRestResponse.success(userService.searchUsers(username));

    }

    /**
     * 根据ID删除用户（逻辑删除）
     *
     * @param id
     * @return
     */
    @PostMapping("/delete")
    public ApiRestResponse deleteUser(@RequestParam long id, HttpServletRequest request) {

        // 管理员鉴权
        if (!isAdmin(request)) {
            // 非管理员返回空数据
            return ApiRestResponse.error(UserCenterExceptionEnum.DEFAULT_ERROR_CODE, "用户不是管理员，不允许删除");
        }
        return ApiRestResponse.success(userService.deleteUser(id));

    }

    /**
     * 描述：校验是否为管理员
     *
     * @param request
     * @return
     */
    private boolean isAdmin(HttpServletRequest request) {
        // 管理员权限鉴权
        User user = (User) request.getSession().getAttribute(UserContant.USER_LOGIN_STATE);
        if (user == null || user.getUserRole() != UserContant.ADMIN_ROLE) {
            return false;
        }
        return true;
    }


}
